// 管理员
const express = require('express');
const router = express.Router()
const { v4: uuidv4 } = require('uuid');
const { db } = require('../db/DbConnect');

router.post('/login', async (req, res) => {
    // 获取账号密码
    let { account, password } = req.body
    try {
        // 查询admin
        let select_admin_sql = `SELECT * FROM admin WHERE 
        account =? AND password =?`
        let _dbres = await db.async.all(
            select_admin_sql, [account, password])

        if (_dbres.length > 0) {
            // 生成uuid， 作为token
            let login_token = uuidv4()
            // 更新token
            let update_token_sql = `
            UPDATE admin SET token =? WHERE id =?`
            await db.async.run(
                update_token_sql, [login_token, _dbres[0].id])
            // 返回信息
            let admin_info = _dbres[0]
            delete admin_info.password
            admin_info.token = login_token

            res.status(200).send({
                code: 200,
                msg: '登录成功',
                admin_info
            })
        } else {
            throw new Error('账号或密码有误')
        }
    } catch (error) {
        res.status(500).send({
            code: 500,
            msg: '登录失败',
            error: error.message
        })
    }
})

module.exports = router